export default {
    namespaced: true,
    state: () => ({
        items: []
    }),
    mutations: {
        ADD_TO_CART(state, snack) {
            const existingItem = state.items.find(item => item.id === snack.id)
            if (existingItem) {
                // 检查库存限制
                if (existingItem.quantity < snack.stock) {
                    existingItem.quantity++
                }
            } else {
                state.items.push({
                    ...snack,
                    quantity: 1
                })
            }
        },
        REMOVE_FROM_CART(state, snackId) {
            const index = state.items.findIndex(item => item.id === snackId)
            if (index > -1) {
                state.items.splice(index, 1)
            }
        },
        UPDATE_QUANTITY(state, { snackId, quantity }) {
            const item = state.items.find(item => item.id === snackId)
            if (item) {
                // 确保数量在合理范围内（1到库存量）
                item.quantity = Math.min(Math.max(1, quantity), item.stock)
            }
        },
        CLEAR_CART(state) {
            state.items = []
        }
    },
    getters: {
        cartTotal: (state) => {
            return state.items.reduce((total, item) => {
                return total + (item.price * item.quantity)
            }, 0).toFixed(2) // 保留两位小数
        },
        cartItemCount: (state) => {
            return state.items.reduce((count, item) => count + item.quantity, 0)
        },
        // 新增一些零食相关的 getters
        cartWeight: (state) => {
            return state.items.reduce((total, item) => {
                return total + (item.weight * item.quantity)
            }, 0)
        },
        cartItemsByCategory: (state) => {
            return state.items.reduce((acc, item) => {
                if (!acc[item.category]) {
                    acc[item.category] = []
                }
                acc[item.category].push(item)
                return acc
            }, {})
        },
        isStockAvailable: (state) => (snackId) => {
            const item = state.items.find(item => item.id === snackId)
            return item ? item.quantity < item.stock : true
        }
    }
}